import { Button, Tooltip, Popconfirm, message } from 'antd';
import { useTranslation } from 'react-i18next';
import { XBorder, Delete } from 'refly-icons';
import cn from 'classnames';
import { useCallback, useState } from 'react';
import { useCanvasContext } from '@refly-packages/ai-workspace-common/context/canvas';
import { CreateVariablesModal } from '../../workflow-variables/create-variables-modal';
import type {
  WorkflowVariable,
  VariableValue,
  VariableResourceType,
  DriveFile,
} from '@refly/openapi-schema';
import { useFetchDriveFiles } from '@refly-packages/ai-workspace-common/hooks/use-fetch-drive-files';
import getClient from '@refly-packages/ai-workspace-common/requests/proxiedRequest';
import { useCanvasResourcesPanelStoreShallow } from '@refly/stores';
import { useVariablesManagement } from '@refly-packages/ai-workspace-common/hooks/use-variables-management';

export const FileItemAction = ({
  file,
  className,
}: {
  file: DriveFile;
  className?: string;
}) => {
  const { t } = useTranslation();
  const { canvasId } = useCanvasContext();

  const [isDeleting, setIsDeleting] = useState(false);
  const { refetch: refetchFiles } = useFetchDriveFiles();
  const { data: workflowVariables } = useVariablesManagement(canvasId);

  const { setCurrentFile } = useCanvasResourcesPanelStoreShallow((state) => ({
    setCurrentFile: state.setCurrentFile,
  }));

  // Add state for modal visibility
  const [isCreateVariableModalVisible, setIsCreateVariableModalVisible] = useState(false);

  const handleCreateVariable = useCallback((_file: DriveFile) => {
    // Open the create variable modal
    setIsCreateVariableModalVisible(true);
  }, []);

  const handleDeleteFile = useCallback(
    async (file: DriveFile) => {
      if (isDeleting) return;
      setIsDeleting(true);
      try {
        await getClient().deleteDriveFile({ body: { fileId: file.fileId } });
        setIsDeleting(false);
        message.success(t('common.deleteSuccess'));

        refetchFiles();
        setCurrentFile(null);
      } finally {
        setIsDeleting(false);
      }
    },
    [isDeleting, refetchFiles, setCurrentFile, t],
  );

  // Create default variable data for the current resource
  const getDefaultVariableData = useCallback((): WorkflowVariable | undefined => {
    if (!file?.fileId) return undefined;

    // Check if resource is already used in workflow variables
    const existingVariable = workflowVariables.find((variable) => {
      if (variable?.variableType !== 'resource') return false;

      return variable.value?.some((value) => {
        if (value?.type === 'resource' && value.resource?.storageKey === file.storageKey) {
          return true;
        }
        return false;
      });
    });

    // If variable already exists, return the existing variable data
    if (existingVariable) {
      return existingVariable;
    }

    // Get file extension and determine file type for new variable
    const fileName = file.name;
    const fileExtension = fileName.split('.').pop()?.toLowerCase() || '';

    // Determine resource type based on file extension
    let resourceType: VariableResourceType = 'document';
    if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'].includes(fileExtension)) {
      resourceType = 'image';
    } else if (['mp3', 'wav', 'ogg', 'aac'].includes(fileExtension)) {
      resourceType = 'audio';
    } else if (['mp4', 'avi', 'mov', 'wmv'].includes(fileExtension)) {
      resourceType = 'video';
    }

    // Create variable value from the current resource
    const variableValue: VariableValue[] = [
      {
        type: 'resource',
        resource: {
          name: fileName,
          storageKey: file.storageKey || '',
          fileType: resourceType,
          entityId: file.fileId,
        },
      },
    ];

    const variable =
      workflowVariables.filter((variable) => variable?.resourceTypes?.includes(resourceType)) || [];

    return {
      variableId: '', // Will be generated by the modal
      name: resourceType + (variable.length + 1).toString(), // User will input
      value: variableValue,
      description: '',
      variableType: 'resource',
      required: true,
      resourceTypes: [resourceType], // Set specific resource type based on file
      isSingle: true,
      options: [],
    };
  }, [file, workflowVariables]);

  const handleModalClose = useCallback((visible: boolean) => {
    setIsCreateVariableModalVisible(visible);
  }, []);

  // Check if current resource is already used in workflow variables
  const isResourceAlreadyUsed = useCallback(() => {
    if (!workflowVariables.length || !file?.fileId) return false;

    // Check all resource type variables for matching storageKey
    return (
      workflowVariables.some((variable) => {
        if (variable?.variableType !== 'resource') return false;

        return variable.value?.some((value) => {
          if (value?.type !== 'resource' || !value.resource) {
            return false;
          }
          const resourceVal = value.resource;
          if (resourceVal.entityId) {
            return resourceVal.entityId === file.fileId;
          }
          return resourceVal.storageKey === file.name;
        });
      }) || false
    );
  }, [workflowVariables, file]);

  // Get tooltip text based on resource usage status
  const getTooltipText = useCallback(() => {
    if (isResourceAlreadyUsed()) {
      return t('canvas.nodeActions.alreadyCreated') || 'Already Created';
    }
    return t('canvas.nodeActions.createVariable') || 'Create Variable';
  }, [isResourceAlreadyUsed, t]);

  return (
    <>
      <div
        className={cn(
          'items-center gap-1 hidden transition-opacity flex-shrink-0 group-hover:flex',
          className,
        )}
      >
        <Tooltip title={getTooltipText()} arrow={false}>
          <Button
            type="text"
            size="small"
            icon={<XBorder size={16} />}
            onClick={(e) => {
              e.stopPropagation();
              handleCreateVariable(file);
            }}
          />
        </Tooltip>
        <Popconfirm
          title={t('canvas.nodeActions.resourceDeleteConfirm', {
            title: file?.name || t('common.untitled'),
          })}
          onConfirm={async (e) => {
            e?.stopPropagation();
            await handleDeleteFile(file);
          }}
          onCancel={(e) => {
            e?.stopPropagation();
          }}
          okText={t('common.confirm')}
          cancelText={t('common.cancel')}
        >
          <Tooltip title={t('common.delete')} arrow={false} placement="bottom">
            <Button
              type="text"
              size="small"
              icon={<Delete size={16} />}
              onClick={(e) => e.stopPropagation()}
            />
          </Tooltip>
        </Popconfirm>
      </div>

      {/* Create Variables Modal */}
      <div onClick={(e) => e.stopPropagation()}>
        <CreateVariablesModal
          mode={isResourceAlreadyUsed() ? 'edit' : 'create'}
          visible={isCreateVariableModalVisible}
          onCancel={handleModalClose}
          defaultValue={getDefaultVariableData()}
          variableType="resource"
          disableChangeVariableType
          isFromResource
          onViewCreatedVariable={() => {
            // For resource variables, we can reopen the modal in edit mode
            handleModalClose(false);
            setTimeout(() => {
              handleModalClose(true);
            }, 100);
          }}
        />
      </div>
    </>
  );
};
